<?php
// 应用公共文件

use app\admin\model\Supplier;
use app\common\service\AuthService;
use EasyAdmin\tool\CommonTool;
use think\facade\Cache;
use \Tightenco\Collect\Support\Collection;
use Vtiful\Kernel\Excel;
use think\facade\Env;

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return url($url, $vars, $suffix, $domain)->build();
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('xdebug')) {

    /**
     * debug调试
     * @param string|array $data 打印信息
     * @param string $type 类型
     * @param string $suffix 文件后缀名
     * @param bool $force
     * @param null $file
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/');
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND);
        $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }
}

if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null $name
     * @return array|mixed
     */
    function sysconfig($group, $name = null)
    {
        $where = ['group' => $group];
        $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");
        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $value = \app\admin\model\SystemConfig::where($where)->value('value');
                Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
            } else {
                $value = \app\admin\model\SystemConfig::where($where)->column('value', 'name');
                Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
            }
        }
        return $value;
    }
}

if (!function_exists('array_format_key')) {

    /**
     * 二位数组重新组合数据
     * @param $array
     * @param $key
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }

}

if (!function_exists('auth')) {

    /**
     * auth权限验证
     * @param $node
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {
        $authService = new AuthService(session('admin.id'));
        $check = $authService->checkNode($node);
        return $check;
    }

}
if (!function_exists('collection')) {
    /**
     * Create a collection from the given value.
     *
     * @param mixed $value
     * @return Collection
     */
    function collection($value = null)
    {
        return new Collection($value);
    }
}
/**
 *
 * 获取所有供应商 id为键 名字 为值
 * @return Array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function get_supplier_arr()
{
    $supplier_need_all = Supplier::field('id,name')->select()->toArray();
    $supplier_name_arr = collection($supplier_need_all)->pluck('name', 'id')->toArray();
    return $supplier_name_arr;
}

/**
 *
 * 构建列表页查询的最终where条件,添加基础字段添加表名字
 * @param $where
 * @return array
 */
function build_final_where($where,$table_name){
    $new_where=[];
    collection($where)->whenNotEmpty(function($where)use(&$new_where,$table_name){
        collection($where)->map(function ($v,$k)use(&$new_where,$table_name){
            $new_where[$k] = $v;
            if(!strstr($v[0], '.')){
                $new_where[$k][0] = $table_name.'.'.$v[0];
            }
        });
    });
    return $new_where;
}


/**
 *
 * 添加插件获取上传Excel文件第二行起的所有数据
 * @param $file
 * @return array
 * @author Aze
 */
function get_upload_excel_data($file)
{

    $path = $file->getPath();
    $filename = $file->getFilename();

    $config = [
        'path' => $path // xlsx文件保存路径
    ];

    $excel = new Excel($config);

    //默认获取第一个sheet 并跳过第一行
    $data = $excel->openFile($filename)
        ->openSheet()
        ->setSkipRows(1)
        ->getSheetData();

    return $data;
}

/**
 * 获取上传的临时目录
 * @return false|string
 * @author Aze
 */
function getTmpDir()
{

    $tmp = ini_get('upload_tmp_dir');

    if ($tmp !== False && file_exists($tmp)) {
        return realpath($tmp);
    }
    return realpath(sys_get_temp_dir());

}

/**
 *
 * 导出Excel公共方法
 *  @param string $title
 * @param array $header
 * @param array $data
 * @return Excelfile
 * @author Aze
 */
function exportExcel($title = '', $header = [], $data = [])
{

    $config = [
        'path' => getTmpDir() // xlsx文件保存路径
    ];

    $fileName = $title . '-' . date('Ymd', time()).'.xlsx';
    $excel = new Excel($config);

    // fileName 会自动创建一个工作表，你可以自定义该工作表名称，工作表名称为可选参数
    $filePath = $excel->fileName($fileName)
        ->header($header)
        ->data($data)
        ->output();

    // Set Header
    header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    header('Content-Disposition: attachment;filename="' . $fileName . '"');
    header('Content-Length: ' . filesize($filePath));
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    header('Cache-Control: max-age=0');
    header('Pragma: public');

    ob_clean();
    flush();

    if (copy($filePath, 'php://output') === false) {
//            Throw FileException::class;
    }

// Delete temporary file
    @unlink($filePath);

}
